昨天的課程 [Day 68] [React] 改變不同部分組成的狀態 (Complex State) 說明了複雜狀態如何傳遞資料,今天延續昨日內容的練習。
//CHALLENGE: Make the code in App.jsx work.
//The final app should have a single contact
//with fName, lName and email.
//HINT: You'll need to apply the following things you learnt:
//1. Using JS Objects with state.
//2. Making use of previous state when changing state.
//3. Working with forms in React.
//4. Handing events
完成的樣子應該要是以下畫面:
以及:
<p>
裡面<input>
裡面加上 onChange
我的第一步是從最後的欄位結果開始:
<input onChange={handleChange} name="fName" placeholder="First Name" />
<input onChange={handleChange} name="lName" placeholder="Last Name" />
<input onChange={handleChange} name="email" placeholder="Email" />
加上 onChange 之後,再回頭想 handleChange
function。
handleChange
function先寫好遇到 fName,lName,email 要做的事:
function handleChange(event){
const {value, name}=event.target;
setContact((preValue)=>{
if (name === "fName"){
}else if (name === "lName"){
}else if (name === "email"){
}
})
}
接著再詳細寫好要 return 的內容:
function handleChange(event){
const {value, name}=event.target;
setContact((preValue)=>{
if (name === "fName"){
return {
fName: value,
lName: preValue.lName,
email: preValue.email
};
}else if (name === "lName"){
return {
fName: preValue.fName,
lName: value,
email: preValue.email
};
}else if (name === "email"){
return {
fName: preValue.fName,
lName: preValue.lName,
email: value
};
}
})
}
OK DONE! 以上是最後完成的截圖~